/**
 * Created by Administrator on 2017/08/16 .
 */

'use strict';
var React = require('react-native');
import net from 'net';
var map = new Map();
import  ProtobufJsManager from "../proto/ProtobufJsManager"
import  theme from '../config/theme'

var {
    NativeEventEmitter,
    NativeModules
} = require('react-native');
var Sockets = NativeModules.TcpSockets;
class TcpManager {

    constructor() {
        this.client = null
        this.tcpReady = false
        this._eventEmitter = new NativeEventEmitter(Sockets);

        this._eventEmitter.addListener('data', ev => this.receive(ev.data))
        this.sn = "";

        this.data = ""

        this.datalengthz = 0;
        this.currentdatalenghth = 0;
        this.loopcount = 0;

        this.longstatus = false
    }


    clientConnect(ip, port, sn) {
        //   return new Promise((fulfill, reject) => {
        return new Promise((fulfill, reject) => {
            this.tcpReady = false


            this.clientDisconect()
            this.client = net.createConnection({host: ip, port: port}, () => {
                // this.updateChatter('opened client on ' + JSON.stringify(client.address()));
                //  client.write('Hello, server! Love, Client.');
                this.tcpReady = true;
                this.sn = sn
                console.log("zzz", "connnect")
                fulfill(this.client)


                // fulfill(client)
            });
            // client.on('data', (data) => {
            //     this.updateChatter('Client Received: ' + data);
            //
            //     // this.client.destroy(); // kill client after server's response
            //     // this.server.close();
            // });
            // client.on('data', (data) => this.receive(data))

            //client.on('data', (data) => console.log("data", data))


            this.client.on('error', (error) => {
                this.tcpReady = false
                this.sn = ""

                console.log("tcp error")
                reject(error)
            });

            this.client.on('close', () => {
                this.tcpReady = false
                this.sn = ""
                console.log("tcp close")
                reject("close")
            });

            //this.client = client;
            //return client
            //  return this.client


        })


        // })
    }

    isSnReady(sn) {
        return this.tcpReady && this.sn == sn
    }


    send(loopcount, cmd, callback, iflongstatus) {
        if (this.tcpReady) {

            this.longstatus = iflongstatus
            this.client.write(cmd);
            map.set(loopcount, callback);
        }


    }


    receive(zz) {
        console.log("tcp manager receive:", zz)

        // let zzz = Object.keys(zz).sort();
        //
        // let str = ""
        // console.log(zzz)
        //
        //
        // for (let i = 0; i < zzz.length; i++) {
        //     console.log("intvalue", zz[i + ""])
        //
        //     console.log("hexvalue", parseInt(zz[i + ""].toString(16)))
        //
        //     let m = ( parseInt(zz[i + ""].toString(16)) - 30).toString(16)
        //
        //     console.log("charat", m)
        //     str += m + "";
        //
        // }
        // console.log("str", str)


        this.data = this.data + zz


        if (!this.longstatus) {
            if (zz.startsWith("08")) {
                if (this.data != "") {
                    this.data = zz
                    this.datalengthz = 0;
                    this.currentdatalenghth = 0;
                }
            }


            ProtobufJsManager.parseMessage(this.data, ProtobufJsManager.headerType.SnapDevice).then((result) => {
                console.log('parse receive', result);


                let callback = (map.get(result.loopCount))
                if (callback) {
                    callback(result)
                    //map.delete(result.loopcount)
                } else {
                    console.log("callback is null")
                }
                this.data = ""

            }, (error) => {
                this.data = ""
                console.log("error=" + error)
            });

        } else {


            if (zz.startsWith("23363a") || zz.startsWith("23373a") || zz.startsWith("23393a")) {

                this.datalengthz = 0;
                this.currentdatalenghth = 0;


                let dataheader = zz.substring(0, 46)
                console.log(dataheader.substring(6, 22), dataheader.substring(22, 26), dataheader.substring(26, 30), dataheader.substring(30, 46))
//#6： + 时间戳 + loopcount + 内容枚举 + 文件长度


                let timestart = theme.getHexFromAscii(dataheader.substring(6, 22))


                let loopcount = theme.getHexFromAscii(dataheader.substring(22, 26))

                let groups = theme.getHexFromAscii(dataheader.substring(26, 30))

                let length = theme.getHexFromAscii(dataheader.substring(30, 46))


                console.log(timestart, loopcount, groups, parseInt(length, 16))


                this.datalengthz = parseInt(length, 16)
                this.loopcount = parseInt(loopcount, 16)

                console.log("this.datalengthz", this.datalengthz)

                this.currentdatalenghth = this.currentdatalenghth + zz.length


            } else {

                //   this.
                this.currentdatalenghth = this.currentdatalenghth + zz.length
//648023
                console.log("this.currentdatalenghth", this.currentdatalenghth)
                if (this.datalengthz == this.currentdatalenghth / 2) {
                    console.log("长度居然对上了sssddfsfsfasfafafafa")
                    this.datalengthz = 0;
                    this.currentdatalenghth = 0;
                    //  先callback
                    let callback = (map.get(this.loopcount))
                    if (callback) {
                        callback(this.data)
                        //map.delete(result.loopcount)
                    } else {
                        console.log("callback is null")
                    }

                    this.data = ""
                    this.longstatus = false

                }

            }
        }


    }


    clientDisconect() {
        this.tcpReady = false
        this.sn = ""
        this.client && this.client.destroy(); // kill client after server's response
        // this.client && this.client.close();
        this.client = null
    }
}
module.exports = new TcpManager();